package cn.orange.ch08_backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * LC39.组合总和
 */
public class LC39 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        LinkedList<Integer> trace = new LinkedList<>();
        backtracking(0, candidates, target, trace, ans);
        return ans;
    }

    private void backtracking(int start, int[] candidates, int target, LinkedList<Integer> trace, List<List<Integer>> ans) {
        if (target < 0) return;
        if (target == 0) {
            ans.add(new ArrayList<>(trace));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            int candidate = candidates[i];
            trace.add(candidate);
            backtracking(i, candidates, target - candidate, trace, ans);
            trace.removeLast();
        }
    }

    public static void main(String[] args) {
        LC39 alg = new LC39();
        System.out.println(alg.combinationSum(new int[]{2, 3, 6, 7}, 7));
        System.out.println(alg.combinationSum(new int[]{2, 3, 5}, 8));
    }
}
